package com.eims.sls_app.ui;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.NetWork;
import com.eims.sls_app.view.MyToast;


import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import bls.juejin.cn.R;

/**
 * Created by lenovo on 2019/11/11.
 */

public class MoneyZcActivity extends MyBaseActivity implements View.OnClickListener {


    private ImageButton ibBack;
    private EditText etUserName;
    private Button btnSure;
    private String username, acount, balance;

    private String opt, auth, info, time, imei, crc; // 格式化后的参数

    private ProgressDialog mProgress = null;
    private MyHandler myHandler;
    private MyHandlerBuy myHandlerBuy;


    private Map<String, String> map = new HashMap<>();

    private TextView tvNum1, tvNum2, tvNum3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.money_zc);
        App.activityS.add(this);
        etUserName = (EditText) findViewById(R.id.et_userName);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        balance = bundle.getString("balance", "0");
        Log.e("--", "onCreate: " + balance);
        if (!balance.equals("0") && !balance.equals("")) {

            etUserName.setHint("请输入转存金额，最高" + balance);

        }

        etUserName.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable edt) {
                String temp = edt.toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 2) {
                    edt.delete(posDot + 3, posDot + 4);
                }
            }

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
        });
        ibBack = (ImageButton) findViewById(R.id.btn_back);


        btnSure = (Button) findViewById(R.id.btn_sure);
        tvNum1 = (TextView) findViewById(R.id.tv_num1);
        tvNum2 = (TextView) findViewById(R.id.tv_num2);
        tvNum3 = (TextView) findViewById(R.id.tv_num3);


        ibBack.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        time = RspBodyBaseBean.getTime();
        imei = RspBodyBaseBean.getIMEI(MoneyZcActivity.this);
        myHandler = new MyHandler();
        myHandlerBuy = new MyHandlerBuy();
        if (NetWork.isConnect(MoneyZcActivity.this)) {
            MyAsynTask myAsyn = new MyAsynTask();
            myAsyn.execute();
        } else {
            MyToast.getToast(MoneyZcActivity.this, "网络异常,获取信息失败").show();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_sure:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                doTransfer();

                break;


        }
    }

    /**
     * 转存
     */
    private void doTransfer() {
        username = etUserName.getText().toString().trim();


        if (username.length() == 0) {
            MyToast.getToast(MoneyZcActivity.this, "转存金额不能为空").show();
            return;
        }
        if (Double.parseDouble(balance) < Double.parseDouble(username)) {
            MyToast.getToast(MoneyZcActivity.this, "金额不能大于账户余额").show();
            return;
        }


        if (NetWork.isConnect(MoneyZcActivity.this)) {
            MyAsynTaskBuy myAsyn = new MyAsynTaskBuy();
            myAsyn.execute();
        } else {
            MyToast.getToast(MoneyZcActivity.this, "网络异常,获取失败").show();
        }
    }


    /**
     * 异步任务
     */
    class MyAsynTask extends AsyncTask<Void, Integer, String> {
        /**
         * 在后台执行的程序
         */
        @Override
        protected String doInBackground(Void... params) {
            // 对密码进行MD5加密

            opt = "117";
            String key = App.key;
            info = "";
            crc = RspBodyBaseBean.getCrc(time, imei, key, info,
                    App.user.getUid());
            auth = RspBodyBaseBean.getAuth(crc, time, imei,
                    App.user.getUid());

            String[] values = {opt, auth, info};
            Log.i("login", "登录info---" + info);
            String result = HttpUtils.doPost(App.names, values,
                    App.path);
            Log.e("login", "登录result---" + result);
            if ("-500".equals(result))
                return "-500";

            try {
                map.clear();

                JSONArray item = new JSONArray(result);
                for (int i = 0; i < item.length(); i++) {
                    JSONObject jsonObject = item.getJSONObject(i);

                    map.put(jsonObject.optString("Key"), jsonObject.optString("Value"));


                }


                return "0";

            } catch (Exception ex) {

                return "-110";
            }
        }

        /**
         * 最开始执行的
         */
        @Override
        protected void onPreExecute() {
            mProgress = BaseHelper.showProgress(MoneyZcActivity.this, null,
                    "加载中....", true, true);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO 这里要传递msg
            try {
                int error = Integer.parseInt(result);
                myHandler.sendEmptyMessage(error);
            } catch (Exception e) {

                MyToast.getToast(MoneyZcActivity.this, result).show();
            }
            // myHandler.sendEmptyMessage(Integer.parseInt(result));
            mProgress.dismiss();
            super.onPostExecute(result);
        }
    }

    /**
     * 处理页面显示的
     */
    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            switch (msg.what) {
                case 0:
                    Log.e("login", "handleMessage: " + map.toString());
                    String textStr1 = "1、转存1-4999元赠送<strong><font color=\"#000000\">" + map.get("zc1") + "%</font></strong>红包;";
                    String textStr2 = "2、转存5000-9999元赠送<strong><font color=\"#000000\">" + map.get("zc2") + "%</font></strong>红包;";
                    String textStr3 = "3、转存10000元以上赠送<strong><font color=\"#000000\">" + map.get("zc3") + "%</font></strong>红包;";


                    tvNum1.setText(Html.fromHtml(textStr1));
                    tvNum2.setText(Html.fromHtml(textStr2));
                    tvNum3.setText(Html.fromHtml(textStr3));


                    break;

                default:

                    MyToast.getToast(MoneyZcActivity.this, "获取信息失败！").show();
                    break;
            }
            super.handleMessage(msg);
        }
    }
    String  msgInfo;
    /**
     * 异步任务
     */
    class MyAsynTaskBuy extends AsyncTask<Void, Integer, String> {
        /**
         * 在后台执行的程序
         */
        @Override
        protected String doInBackground(Void... params) {
            // 对密码进行MD5加密

            opt = "118";
            String key = App.key;
            info = username;
            crc = RspBodyBaseBean.getCrc(time, imei, key, info,
                    App.user.getUid());
            auth = RspBodyBaseBean.getAuth(crc, time, imei,
                    App.user.getUid());

            String[] values = {opt, auth, info};
            Log.i("login", "登录info---" + info);
            String result = HttpUtils.doPost(App.names, values,
                    App.path);
            Log.e("login", "登录result---" + result);
            if ("-500".equals(result))
                return "-500";

            try {


                JSONObject jsonObject=new JSONObject(result);
                msgInfo =jsonObject.optString("msg");


                return "0";

            } catch (Exception ex) {

                return "-110";
            }
        }

        /**
         * 最开始执行的
         */
        @Override
        protected void onPreExecute() {
            mProgress = BaseHelper.showProgress(MoneyZcActivity.this, null,
                    "加载中....", true, true);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO 这里要传递msg
            try {
                int error = Integer.parseInt(result);
                myHandlerBuy.sendEmptyMessage(error);
            } catch (Exception e) {

                MyToast.getToast(MoneyZcActivity.this, result).show();
            }
            // myHandler.sendEmptyMessage(Integer.parseInt(result));
            mProgress.dismiss();
            super.onPostExecute(result);
        }
    }

    /**
     * 处理页面显示的
     */
    @SuppressLint("HandlerLeak")
    class MyHandlerBuy extends Handler {
        @Override
        public void handleMessage(Message msg) {
            mProgress.dismiss();
            switch (msg.what) {
                case 0:
                    MyToast.getToast(MoneyZcActivity.this, msgInfo+"").show();

                    if(msgInfo.contains("成功")){

                        finish();
                    }


                    break;

                default:

                    MyToast.getToast(MoneyZcActivity.this, "转存失败！").show();
                    break;
            }
            super.handleMessage(msg);
        }
    }
}